import itertools
from itertools import chain

from core.documents import APIModel


def get_ask_by_index(url, ask_index):
    from core.documents import Ask
    ask_count = Ask.objects(url=url).count()
    if ask_count:
        if ask_index >= ask_count:
            ask_index = ask_count - 1
        elif ask_index < 0:
            ask_index = 0
        ask = Ask.objects(url=url)[ask_index]
        return ask


def get_data_by_route(data, route):
    td = data
    for i, r in enumerate(route):
        td = td[r]
    return td


def get_data_route(data):
    """获取参数的路由"""
    if isinstance(data, dict):
        for key in data:
            t = [key]
            t.extend(get_data_route(data[key]))
            yield t
    if isinstance(data, list):
        for i in range(len(data)):
            t = [i]
            t.extend(get_data_route(data[i]))
            yield t
    return []


def max_length(content, size):
    if content:
        if len(content) > size:
            return content[:size] + '...'
    return content


def get_data_by_routes(data, routes, all_have=True):
    """

    :param data:
    :param routes:
    :param all_have: 所有的路由都要获取到
    :return:
    """
    res = type(data)()
    for route in routes:
        try:

            tr = res
            td = data
            for i, r in enumerate(route):
                if i < len(route) - 1:
                    tr[r] = type(td[r])()
                    tr = tr[r]
                    td = td[r]
                else:
                    tr[r] = td[r]
        except:
            if all_have:
                return None
    return res


def get_all_combinations(items, s_to_m=True):
    if s_to_m:
        ite = range(1, len(items))
    else:
        ite = range(len(items) - 1, 0, -1)
    for i in ite:
        yield from itertools.combinations(items, i)


def get_model_struct():
    # 获取模型的url结构
    res = {}
    for item in APIModel.objects():
        tr = res
        url = item.get_relate_url().split('/')
        if len(url) < 3:
            url += [''] * (3 - len(url))
        lv = 0
        for i in chain(url[:2], ['/'.join(url)]):
            lv += 1
            if lv == 3:
                tr[i] = item
            else:
                if i not in tr:
                    tr[i] = {}
            tr = tr[i]
    # 最高3级
    return res


if __name__ == '__main__':
    get_model_struct()
